package tools;

//可以将要发送的信息进行封装成一个类  在对这个类进行序列化和反序列化
public class MsgPacket extends Packet{
	public String from;//谁发来的
	public String msg;//信息
	public String to;//发给谁

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public byte[] serialize() {
		int totalLength = 16 + from.getBytes().length + msg.getBytes().length + to.getBytes().length;

		byte[] buffer = new byte[totalLength];

		int offset = 0;

		// copy totalLength to buffer
		byte[] totalLengthBuffer = Util.int2bytes(totalLength);
		System.arraycopy(totalLengthBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy packet type to buffer
		byte[] packetTypeBuffer = Util.int2bytes(Service.PACKET_TYPE.C2S_MSG);
		System.arraycopy(packetTypeBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy user name length to buffer
		byte[] fromLengthBuffer = Util.int2bytes(from.getBytes().length);
		System.arraycopy(fromLengthBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy user name to buffer
		System.arraycopy(from.getBytes(), 0, buffer, offset, from.getBytes().length);
		offset += from.getBytes().length;

		byte[] msgLengthBuffer = Util.int2bytes(msg.getBytes().length);
		System.arraycopy(msgLengthBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy password to buffer
		System.arraycopy(msg.getBytes(), 0, buffer, offset, msg.getBytes().length);
		offset += msg.getBytes().length;

		System.arraycopy(to.getBytes(), 0, buffer, offset, to.getBytes().length);
		offset += to.getBytes().length;

		return buffer;
	}

	public void unserialize(byte[] data) {
		System.out.println(data.length);
		// decode total length
		int totalLength = Util.bytes2int(data, 0);

		// decode user name length
		int fromLength = Util.bytes2int(data, 8);

		from = new String(data, 12, fromLength);

		int msgLength = Util.bytes2int(data, 12+fromLength);

		msg = new String(data, 12 + fromLength, msgLength);

		to = new String(data, 16 + fromLength + msgLength, totalLength - 16 - fromLength - msgLength);
	}
}
